package com.wanpinghui.wphlibrary.common.toast;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.os.Build;
import android.os.Looper;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.wanpinghui.wphlibrary.R;
import com.wanpinghui.wphlibrary.WPHLibrary;
import com.yunshl.yunshllibrary.utils.TextUtil;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/4/24
 * 版本:1.0
 ***/

public class ToastManager {
    private ToastDailog mDialog;
    private RichToastDialog mRichToastDialog;
    private int gravity = Gravity.CENTER;
    private Toast toast;

    public void setGravity(int gravity) {
        this.gravity = gravity;
    }

    private ToastManager() {

    }

    public static ToastManager getInstance() {
        return ToastManagerHolder.manager;
    }

    public void showToast(final String text) {
        if (TextUtil.isEmpty(text))return;
        if (Looper.myLooper() != Looper.getMainLooper()) {
            Observable.create(new Observable.OnSubscribe<String>() {
                @Override
                public void call(Subscriber<? super String> subscriber) {
                    subscriber.onNext(text);
                }
            }).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String textStr) {
                            if (toast == null) {
                                toast = new Toast(WPHLibrary.getLibrary().getContext());
                            }else {
                                toast.cancel();
                                toast = new Toast(WPHLibrary.getLibrary().getContext());
                            }
                            View v = LayoutInflater.from(WPHLibrary.getLibrary().getContext()).inflate(R.layout.view_toast, null);
                            TextView textView = (TextView) v.findViewById(R.id.tv_content);
                            textView.setText(text);
                            toast.setGravity(gravity, 0, 0);
                            toast.setView(v);
                            toast.show();
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {

                        }
                    });
        } else {
            if (toast == null) {
                toast = new Toast(WPHLibrary.getLibrary().getContext());
            }else {
                toast.cancel();
                toast = new Toast(WPHLibrary.getLibrary().getContext());
            }

            View v = LayoutInflater.from(WPHLibrary.getLibrary().getContext()).inflate(R.layout.view_toast, null);
            TextView textView = (TextView) v.findViewById(R.id.tv_content);
            textView.setText(text);
            toast.setGravity(gravity, 0, 0);
            toast.setView(v);
            toast.show();
        }
    }

    public void showToast(Activity context, String text) {
        if (TextUtil.isEmpty(text))return;
        if (haveNoPermission()) {
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
            mDialog = new ToastDailog(context, R.style.ToastDialog);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.setText(text);
            Window win = mDialog.getWindow();
            WindowManager.LayoutParams params = new WindowManager.LayoutParams();
            params.y = 250;//设置y坐标
            win.setAttributes(params);
            mDialog.show();
        } else {
            showToast(text);
        }

    }

    public void showRichToast(Context context, String title, String content, int resId) {

        if (mRichToastDialog != null && mRichToastDialog.isShowing()) {
            mRichToastDialog.dismiss();
        }
        mRichToastDialog = new RichToastDialog(context, R.style.ToastDialog);
        mRichToastDialog.setCanceledOnTouchOutside(true);
        mRichToastDialog.setText(title, content, resId);
        mRichToastDialog.show();
    }

    private static boolean haveNoPermission() {
        if (OsInfoUtil.isMIUI() || OsInfoUtil.checkIsMeizuRom() || OsInfoUtil.checkIsHuaweiRom()) {
            if (Build.VERSION.SDK_INT >= 19) {
                return !isNotificationEnabled(WPHLibrary.getLibrary().getContext());
            }
        }
        return false;
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {
        final String CHECK_OP_NO_THROW = "checkOpNoThrow";
        final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;
        Class appOpsClass = null; /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (int) opPostNotificationValue.get(Integer.class);
            return ((int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static class ToastManagerHolder {
        public static final ToastManager manager = new ToastManager();
    }
}
